﻿/*
 * Copyright (C) 2009-2010 Valerio Fuoglio <valerio.fuoglio@gmail.com>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Lastfm.Scrobbling;
using Lastfm.Services;

namespace LightScrobbler
{
    internal partial class SendForm : Form
    {
        #region Delegates

        public delegate void EndCallback();

        public delegate void ProgressBarSetMaxCallback(int maxValue);

        public delegate void ProgressBarStepCallback();

        public delegate void UpdateStatusTextCallback(string status);

        #endregion

        private readonly Thread _threadSend;

        public SendForm()
        {
            InitializeComponent();
            MinimumSize = Size;
            _progressBar.Step = 1;

            _threadSend = new Thread(Send);
            // Thread can be started only after all has been shown
            Shown += StartThread;
        }

        private void StartThread(object sender, EventArgs e1)
        {
            _threadSend.Start();
            // _threadPostSend.Start();
        }

        private void Send()
        {
            string API_KEY = Utils.ApiKey;
            string API_SECRET = Utils.ApiSecret;
            Version ver = Assembly.GetExecutingAssembly().GetName().Version;
            string clientId = Utils.ClientId;

            string username = ScrobbleSessionData.GetInstance().Username;
            string password = ScrobbleSessionData.GetInstance().Password;
            List<Entry> selectedTracks = ScrobbleSessionData.GetInstance().SelectedTracks;


            Session session = ScrobbleSessionData.GetInstance().Session;

            switch (ScrobbleSessionData.GetInstance().SessionState)
            {
                case SessionState.AuthenticationFailed:
                    MessageBox.Show("Wrong username or password.",
                                    "Authentication failed", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                    ScrobbleSessionData.GetInstance().SuccessifullySent = false;
                    return;
                case SessionState.Unavailable:
                    MessageBox.Show("Cannot connect to LastFm scrobbling service. Please try again later.",
                                    "Service Offline", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                    ScrobbleSessionData.GetInstance().SuccessifullySent = false;
                    return;
                case SessionState.NoNetwork:
                    MessageBox.Show("Cannot connect to LastFm scrobbling service. Please try again later.",
                                    "Service Offline", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                    ScrobbleSessionData.GetInstance().SuccessifullySent = false;
                    return;
            }

            Connection connection = null;

            try
            {
                connection = new Connection(clientId, ver.ToString(), username, session);
                connection.Initialize();
            }
            catch (BannedClientException)
            {
                MessageBox.Show("This client has been banned, please contact its producer for any question.",
                                "Banned client", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1);
                ScrobbleSessionData.GetInstance().SuccessifullySent = false;
                return;
            }

            BeginInvoke(new ProgressBarSetMaxCallback(ProgressBarSetMax), new object[] {selectedTracks.Count});

            int i = 1;
            foreach (Entry track in selectedTracks)
            {
                string statusText = "Scrobbling (" + i++ + " of " + selectedTracks.Count + "): " + track;
                _statusLabel.BeginInvoke(new UpdateStatusTextCallback(UpdateStatusText), new object[] {statusText});

                try
                {
                    connection.Scrobble(track);
                }
                catch (WrongTimeException e)
                {
                    ScrobbleSessionData.GetInstance().RejectedTracks.Add(track, e.Message);
                }
                catch (ScrobblingException e)
                {
                    ScrobbleSessionData.GetInstance().RejectedTracks.Add(track, e.Message);
                }
                catch (Exception e)
                {
                    MessageBox.Show("An unidentified error happened. Exception's message: { " + e.Message + " }",
                                    "Unidentified error", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                    ScrobbleSessionData.GetInstance().SuccessifullySent = false;
                    return;
                }
                finally
                {
                    BeginInvoke(new ProgressBarStepCallback(ProgressBarStep), null);
                }
            }

            // If all tracks are rejected, it cannot be account as a success :P
            if (ScrobbleSessionData.GetInstance().RejectedTracks.Count == selectedTracks.Count)
                ScrobbleSessionData.GetInstance().SuccessifullySent = false;
            else
                ScrobbleSessionData.GetInstance().SuccessifullySent = true;

            string finalMessage;

            if (ScrobbleSessionData.GetInstance().SuccessifullySent)
                finalMessage = "All tracks submitted successfully";
            else
                finalMessage = "Some errors occurred";

            BeginInvoke(new UpdateStatusTextCallback(UpdateStatusText),
                        new object[] {finalMessage});
            BeginInvoke(new EndCallback(End), null);
        }

        private void ProgressBarSetMax(int maxValue)
        {
            _progressBar.Maximum = maxValue;
        }

        private void UpdateStatusText(string status)
        {
            _statusLabel.Text = status;
        }

        private void ProgressBarStep()
        {
            _progressBar.PerformStep();
        }

        private void End()
        {
            _threadSend.Join();

            // Remove log file if requested

            if ((bool) ScrobbleSessionData.GetInstance().Options[LightScrobblerOptions.DeleteLogFile] &&
                ScrobbleSessionData.GetInstance().SuccessifullySent)
            {
                string filePath = ScrobbleSessionData.GetInstance().FilePath;

                try
                {
                    File.Delete(filePath);
                }
                catch (IOException)
                {
                    MessageBox.Show("Cannot delete " + filePath + " : file is currenty in use.",
                                    "Cannot delete log file", MessageBoxButtons.OK, MessageBoxIcon.Warning,
                                    MessageBoxDefaultButton.Button1);
                }
                catch (UnauthorizedAccessException)
                {
                    MessageBox.Show(
                        "Cannot delete " + filePath +
                        " : you may not have the required permission or log file is read-only.",
                        "Cannot delete log file", MessageBoxButtons.OK, MessageBoxIcon.Warning,
                        MessageBoxDefaultButton.Button1);
                }

                MessageBox.Show("All tracks submitted successfully.", "Success", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }

            Close();
        }
    }
}